package com.umeox.watch.moto.chat.ui;

import static com.umeox.watch.moto.chat.utils.Constants.EXTRA_FILE_PATH;

import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.common.rvadapter.MultiItemTypeAdapter;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.watch.moto.chat.R;
import com.umeox.watch.moto.chat.adapter.ChatContactsAdapter;
import com.umeox.watch.moto.chat.db.ContactInfo;
import com.umeox.watch.moto.chat.db.DBUtils;
import com.umeox.watch.moto.chat.event.ContactRefreshEvent;
import com.umeox.watch.moto.chat.utils.Constants;
import com.umeox.watch.moto.dataservice.DataProvider;
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy;

import org.greenrobot.eventbus.EventBus;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Rambo 2021/10/14
 * Describe:
 */
public class ChatContactListActivity extends ThemeAppCompatActivity implements View.OnClickListener, MultiItemTypeAdapter.OnItemClickListener {

    private ImageView ivRefresh;
    private ImageView ivAdd;
    private ChatContactsAdapter chatContactsAdapter;
    private HandlerThread handlerThread;
    private Handler mHandler;
    private PushApiClientProxy apiClientProxy;

    private ContentObserver buddiesObserver, messageObserver;
    private RecyclerView mChatContactRv;
    private Uri dataUri;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_contacts_list);
        handlerThread = new HandlerThread("get-buddies");
        handlerThread.start();

        mHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 0) {
                    refreshDataSet(true);
                    return true;
                } else if (msg.what == 1) {
                    refreshDataSet(false);
                    return true;
                }
                return false;
            }

            private void refreshDataSet(boolean refresh) {
                final List<ContactInfo> contactList = DBUtils.INSTANCE.getContactList();
                Log.i("chat_data", "refreshData: " + contactList);
                if (contactList.isEmpty()) {
                    runOnUiThread(() -> loadingAnimation());
                    if (apiClientProxy == null) {
                        apiClientProxy = (PushApiClientProxy) PushApiClientProxy.fetchBinder();
                    }
                    try {
                        apiClientProxy.requestGetBuddies();
                    } catch (Exception e) {
                        Logger.e("获取联系人失败>>>" + e);
                    }
                }
                if (!isFinishing()) {
                    runOnUiThread(() -> {
                        if (!isFinishing() && !isDestroyed()) {

                            if (!contactList.isEmpty()) {
                                ivRefresh.setImageDrawable(null);
                                ivRefresh.setVisibility(View.GONE);
                            }
                            Collections.sort(contactList, new Comparator<ContactInfo>() {
                                @Override
                                public int compare(ContactInfo o1, ContactInfo o2) {
                                    if (o1.isGroup() && o2.isGroup()) {
                                        return 0;
                                    } else if (o1.isGroup()) {
                                        return -1;
                                    } else if (o2.isGroup()) {
                                        return 1;
                                    }
                                    return 0;
                                }
                            });
                            chatContactsAdapter.setDatas(contactList);
                            chatContactsAdapter.notifyDataSetChanged();
                            boolean hasDeviceFriend = false;
                            for (ContactInfo contactInfo : contactList) {
                                if (contactInfo.getType() == 2) {
                                    hasDeviceFriend = true;
                                    break;
                                }
                            }

                            if (hasDeviceFriend && DataProvider.getCustomGroup()) {
                                ivAdd.setVisibility(View.VISIBLE);
                            } else {
                                ivAdd.setVisibility(View.GONE);
                            }
                            //发通知
                            Logger.e("send ContactRefreshEvent");
                            EventBus.getDefault().post(new ContactRefreshEvent());
                        }
                    });
                }
            }
        });

        initView();
    }

    private void initView() {
        dataUri = getIntent().getData();
        ivRefresh = findViewById(R.id.ivRefresh);
        ivAdd = findViewById(R.id.iv_add);
        ivRefresh.setOnClickListener(v -> refreshListView());
        mChatContactRv = findViewById(R.id.contactList);
        mChatContactRv.setHasFixedSize(true);
        mChatContactRv.setLayoutManager(new LinearLayoutManager(this));
        chatContactsAdapter = new ChatContactsAdapter(this, null);
        mChatContactRv.setAdapter(chatContactsAdapter);
        chatContactsAdapter.setOnItemClickListener(this);
//        mChatContactRv.post(() -> );
        mHandler.sendEmptyMessage(1);
        registerObserver();
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ChatContactListActivity.this, CreateGroupActivity.class));
            }
        });

    }


    private void registerObserver() {
        if (buddiesObserver == null) {
            //监听联系人数据的监听对象
            buddiesObserver = new ContentObserver(mHandler) {
                @Override
                public void onChange(boolean selfChange) {
                    Logger.d("好友信息发生修改");
                    // 当联系人表发生变化时进行相应的操作
                    refreshListView();
                }
            };
        }

        if (messageObserver == null) {
            //监听消息数据的监听对象
            messageObserver = new ContentObserver(mHandler) {
                @Override
                public void onChange(boolean selfChange) {
                    Logger.d("语聊联系人列表发生改变");
                    // 当联系人表发生变化时进行相应的操作
                    refreshListView();
                }
            };
        }
        //监听好友是否有变化
        DataProvider.BuddyProvider.registerContentObserver(false, buddiesObserver);
        //监听是否有未读消息
        DataProvider.ChatContactProvider.registerContentObserver(false, messageObserver);
    }


    private void loadingAnimation() {
        ivRefresh.setVisibility(View.VISIBLE);
        RotateAnimation rotate = new RotateAnimation(0f,
                360f,
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);
        LinearInterpolator lin = new LinearInterpolator();
        rotate.setInterpolator(lin);
        rotate.setDuration(800);//设置动画持续时间
        rotate.setRepeatCount(-1);//设置重复次数
        rotate.setFillAfter(false);//动画执行完后是否停留在执行完的状态
        ivRefresh.setAnimation(rotate);
        rotate.start();
    }


    private void refreshListView() {
        mHandler.removeMessages(1);
        mHandler.sendEmptyMessage(1);
    }

    private void unRegisterObserver() {
        try {
            getContentResolver().unregisterContentObserver(buddiesObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            getContentResolver().unregisterContentObserver(messageObserver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegisterObserver();
        handlerThread.quit();
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onClick(View v) {
        startActivity(new Intent(ChatContactListActivity.this, PairingActivity.class));
    }

    @Override
    public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
        String intentData = getIntentData();
        if (!TextUtils.isEmpty(intentData)) {
            Intent shareIntent = new Intent(ChatContactListActivity.this, ShareFileActivity.class);
            shareIntent.putExtra(Constants.EXTRA_CONTACT, chatContactsAdapter.getDatas().get(position));
            shareIntent.putExtra(EXTRA_FILE_PATH, intentData);
            startActivity(shareIntent);
            finish();
        } else {
            Intent i = new Intent(ChatContactListActivity.this, WatchMessageActivity.class);
            i.putExtra(Constants.EXTRA_CONTACT, chatContactsAdapter.getDatas().get(position));
            startActivity(i);
        }
    }

    @Override
    public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
        return false;
    }

    /**
     * 从Intent中获取data，判断是否从相册app跳转过来
     * 从相册跳转过来的请求，直接从当前页面调用aidl接口发送照片给好友，不用跳转到第三级页面（好友聊天信息页面）
     */
    public String getIntentData() {
        if (dataUri != null
                && "chat".equals(dataUri.getScheme())
                && "file".equals(dataUri.getHost())) {
            return dataUri.getPath();
        }
        return "";
    }
}
